package cn.wolfcode.controller;


import cn.wolfcode.domain.Exam;
import cn.wolfcode.domain.JsonResult;
import cn.wolfcode.domain.Question;
import cn.wolfcode.enums.QuestionTypeEnum;
import cn.wolfcode.service.IExamService;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.util.RequiredPermission;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;

@Controller
@RequestMapping("/exam")
public class ExamController {

    @Autowired
    private IExamService examService;

    @RequiredPermission(name="添加试卷",expression ="exam:input")
    @RequestMapping("/input")
    public String input(Model model, @ModelAttribute("qo") QueryObject qo){
        return "exam/input";
    }

    @RequestMapping("/delete")
    @RequiredPermission(name="试卷删除",expression ="exam:delete")
    @ResponseBody
    public JsonResult delete(Long id){
        if (id != null) {
            examService.delete(id);
        }
        return new JsonResult();
    }


    @RequestMapping("/saveOrUpdate")
    @RequiredPermission(name="试卷保存",expression ="exam:saveOrUpdate")
    @ResponseBody
    public JsonResult saveOrUpdate(Exam exam){
        Long id = null;
        if (exam.getId() != null) {
            examService.update(exam);
        }else {
            id = examService.save(exam);
        }
        JsonResult jsonResult = new JsonResult();
        jsonResult.setData(id);
        return jsonResult;
    }
    @RequestMapping("/show")
    @RequiredPermission(name="试卷预览",expression ="exam:show")
    public String show(Long id,Model model){
        Exam exam = examService.show(id);
        model.addAttribute("exam",exam);
        //统计单选题的总分
        List<Question> questions = exam.getQuestions();
        HashMap<String, Object> map = new HashMap<>();
        int singleTotalScore = 0;
        int mutipleTotalScore = 0;
        int judgeTotalScore = 0;
        for (Question question : questions) {
            if (QuestionTypeEnum.SINGLE.getValue().equals(question.getType())){
                singleTotalScore += question.getScore();
            }
            if (QuestionTypeEnum.MUTIPLE.getValue().equals(question.getType())){
                mutipleTotalScore += question.getScore();
            }
            if (QuestionTypeEnum.JUDGE.getValue().equals(question.getType())){
             judgeTotalScore  += question.getScore();
            }

        }
        map.put("singleTotalScore",singleTotalScore);
        map.put("mutipleTotalScore",mutipleTotalScore);
        map.put("judgeTotalScore",judgeTotalScore);
        model.addAttribute("map",map);
        return "/exam/show";
    }
}
